package com.hexun.es.controller;

import com.alibaba.fastjson.JSON;
import com.hexun.es.constants.PersonConstant;
import com.hexun.es.enums.ResultEnum;
import com.hexun.es.model.Person;
import com.hexun.es.service.PersonService;
import com.hexun.es.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @description:人口信息控制器
 * @author:yrw
 * @date 2018/11/19
 */

@RestController
@RequestMapping("/person")
public class PersonController {

    @Autowired
    private PersonService personService;

    @RequestMapping("/hello")
    public String hello(){
        return "hello";
    }

    @RequestMapping("/add")
    public String add(Person p){
        Result result = personService.add(p);
        if(result.Success()){
            return ResultEnum.SUCCESS.getDesc();
        }
        return ResultEnum.FAIL.getDesc();
    }

    @RequestMapping("/update")
    public String updateById(Person p){
        if(p == null){
            return "参数不能为空！";
        }

        if(StringUtils.isEmpty(p.getId())){
            return PersonConstant.IDNOTBLANK;
        }
        Result result = personService.update(p);
        if(result.Success()){
            return ResultEnum.SUCCESS.getDesc();
        }
        return ResultEnum.FAIL.getDesc();
    }

    @RequestMapping("/deleteById/{id}")
    public String deleteById(@PathVariable Integer id){
        if(StringUtils.isEmpty(id)){
            return PersonConstant.IDNOTBLANK;
        }
        Result result = personService.deleteById(id);
        if(result.Success()){
            return ResultEnum.SUCCESS.getDesc();
        }
        return ResultEnum.FAIL.getDesc();
    }

    @RequestMapping("/getById/{id}")
    public String getById(@PathVariable Integer id){
        if(StringUtils.isEmpty(id)){
            return PersonConstant.IDNOTBLANK;
        }
        Result result = personService.getById(id);
        if(result.Fail()){
            return result.getMessage();
        }
        return JSON.toJSONString(result.getData());
    }

    @RequestMapping("/findAll")
    public String findAll(){
        Result result = personService.findAll();
        if(result.Fail()){
            return ResultEnum.SUCCESS.getDesc();
        }
        return JSON.toJSONString(result.getData());
    }
}
